package com.example.crm01.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crm01.common.Result;
import com.example.crm01.entity.user;
import com.example.crm01.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.apache.catalina.User;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {


    @Resource
    UserMapper userMapper;

// 用户登录
    @PostMapping("/login")
    public Result<?> login(@RequestBody user louser) {
        user res = userMapper.selectOne(Wrappers.<user>lambdaQuery().eq(user::getUsername,louser.getUsername()).eq(user::getPassword,louser.getPassword()));
        if (res == null){
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success();
    }

// 用户新增
    @PostMapping
    public Result<?> sava(@RequestBody user user) {
            if (user.getPassword() == null) {
                user.setPassword("123456");
            }
            userMapper.insert(user);
            return Result.success();
    }

// 用户更新
    @PutMapping
    public Result<?> update(@RequestBody user user) {
        userMapper.updateById(user);
        return Result.success();
    }

// 分页查询
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<user> wrapper = Wrappers.<user>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(user::getUsername,search);

        }
        Page<user> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(userPage);
    }

// 用户删除
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        userMapper.deleteById(id);
        return Result.success();
    }


}
